/**
 * 用户状态管理
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginWeixin, loginGuest, verifyToken } from '@/api/auth'
import { setStorage as setStorageUtil, getStorage as getStorageUtil, removeStorage as removeStorageUtil } from '@/utils/storage'

const STORAGE_KEYS = {
  TOKEN: 'user_token',
  USER_ID: 'user_id',
  USER_INFO: 'user_info'
}

export const useUserStore = defineStore('user', () => {
  const token = ref('')
  const userId = ref('')
  const userInfo = ref(null)
  const isLoggedIn = ref(false)

  // 初始化
  function init() {
    const savedToken = getStorageUtil(STORAGE_KEYS.TOKEN)
    const savedUserId = getStorageUtil(STORAGE_KEYS.USER_ID)
    const savedUserInfo = getStorageUtil(STORAGE_KEYS.USER_INFO)

    if (savedToken && savedUserId) {
      token.value = savedToken
      userId.value = savedUserId
      userInfo.value = savedUserInfo
      isLoggedIn.value = true
      
      // 异步验证 token，不阻塞初始化
      verifyToken().catch(async () => {
        // token 无效，尝试重新登录
        console.warn('Token 验证失败，尝试重新登录')
        
        // 如果是游客用户，尝试重新登录
        if (savedUserInfo && savedUserInfo.type === 'guest') {
          try {
            const visitorId = getStorageUtil('visitor_id')
            if (visitorId) {
              const platform = getPlatform()
              const res = await loginGuest(visitorId, platform)
              setLoginData(res)
              console.log('游客重新登录成功')
            } else {
              // 没有游客ID，清除登录状态
              logout()
            }
          } catch (err) {
            console.error('重新登录失败:', err)
            // 重新登录失败，清除登录状态
            logout()
          }
        } else {
          // 非游客用户，清除登录状态
          logout()
        }
      })
    }
  }

  // 微信登录
  async function loginWithWeixin() {
    return new Promise((resolve, reject) => {
      // #ifdef MP-WEIXIN
      uni.login({
        provider: 'weixin',
        success: async (loginRes) => {
          if (loginRes.code) {
            try {
              const res = await loginWeixin(loginRes.code)
              setLoginData(res)
              resolve(res)
            } catch (err) {
              reject(err)
            }
          } else {
            reject(new Error('获取登录凭证失败'))
          }
        },
        fail: (err) => {
          reject(new Error(err.errMsg || '登录失败'))
        }
      })
      // #endif
      
      // #ifndef MP-WEIXIN
      reject(new Error('当前平台不支持微信登录'))
      // #endif
    })
  }

  // 游客登录
  async function loginAsGuest() {
    try {
      // 尝试使用已有的游客ID
      let visitorId = getStorageUtil('visitor_id')
      
      if (!visitorId) {
        // 生成新的游客ID
        visitorId = generateVisitorId()
        setStorageUtil('visitor_id', visitorId)
      }
      
      const platform = getPlatform()
      const res = await loginGuest(visitorId, platform)
      setLoginData(res)
      return res
    } catch (err) {
      throw err
    }
  }

  // 设置登录数据
  function setLoginData(data) {
    token.value = data.token
    userId.value = data.userId
    userInfo.value = data.userInfo
    isLoggedIn.value = true

    setStorageUtil(STORAGE_KEYS.TOKEN, data.token)
    setStorageUtil(STORAGE_KEYS.USER_ID, data.userId)
    setStorageUtil(STORAGE_KEYS.USER_INFO, data.userInfo)
  }

  // 退出登录
  function logout() {
    token.value = ''
    userId.value = ''
    userInfo.value = null
    isLoggedIn.value = false

    removeStorageUtil(STORAGE_KEYS.TOKEN)
    removeStorageUtil(STORAGE_KEYS.USER_ID)
    removeStorageUtil(STORAGE_KEYS.USER_INFO)
  }

  // 生成游客ID
  function generateVisitorId() {
    const timestamp = Date.now()
    const random = Math.random().toString(36).substring(2, 15)
    return `${timestamp}_${random}`
  }

  // 获取平台标识
  function getPlatform() {
    // #ifdef MP-WEIXIN
    return 'mp-weixin'
    // #endif
    // #ifdef H5
    return 'h5'
    // #endif
    // #ifdef APP-PLUS
    return 'app-plus'
    // #endif
    return 'unknown'
  }

  // 初始化
  init()

  return {
    token,
    userId,
    userInfo,
    isLoggedIn,
    loginWithWeixin,
    loginAsGuest,
    logout,
    init
  }
})

